import { useUserStore } from '@/stores'
import { baseUrl } from '@/common/config'
import * as dayjs from 'dayjs'

export default {
  data() {
    return {}
  },
  computed: {
    currentUser() {
      return useUserStore().info
    },
    loginState() {
      return useUserStore().loginState
    }
  },
  methods: {
    formatUrl(url: string): string {
      if (url.indexOf('http') !== -1) {
        return url
      } else {
        return `${baseUrl().replace('/api', '')}${url}`
      }
    },
    previewImage(urls: string[], current?: number) {
      uni.previewImage({
        urls,
        current,
        indicator: 'number',
        loop: true
      })
    },
    toPage(url: string, needLogin: boolean = true, mode = 'navigateTo') {
      if (needLogin && !useUserStore().loginState) {
        uni.showToast({
          title: '请完善个人信息～',
          icon: 'none',
          duration: 1500
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/user/editUserInfo/editUserInfo'
          })
        }, 1500)
        return
      }
      if (url) {
        switch (mode) {
          case 'navigateTo':
            uni.navigateTo({ url })
            break
          case 'redirectTo':
            uni.redirectTo({ url })
            break
          case 'switchTab':
            uni.switchTab({ url })
            break
          case 'reLaunch':
            uni.reLaunch({ url })
            break
        }
      }
    },
    back(delta: number = 1) {
      uni.navigateBack({ delta })
    },
    copyText(data: string) {
      uni.setClipboardData({
        data,
        success() {
          uni.showToast({
            title: '已复制到剪切板',
            icon: 'success'
          })
        }
      })
    },
    formatNumber(num: string | number | null, toFix: number = 2): string {
      if (!num) {
        return (0).toFixed(toFix)
      } else {
        return Number(num).toFixed(toFix)
      }
    },
    simplifyNumber(num: number): string {
      if (num < 1000) {
        return num.toString()
      } else if (num < 10000) {
        return (num / 1000).toFixed(0) + '千'
      } else {
        return (num / 10000).toFixed(0) + '万'
      }
    },
    formmatTime(time: number, format: string = 'YYYY-MM-DD HH:mm:ss'): string {
      if (typeof time === 'number' && time.toString().length === 10) {
        return dayjs.unix(time).format(format)
      }
      return dayjs(time).format(format)
    }
  }
}
